package br.com.felinelayer.server;

import br.com.felinelayer.common.Message;
import br.com.felinelayer.common.Protocol;
import br.com.felinelayer.server.application.Application;

/**
 *
 */
public class ApplicationLauncher extends Thread {

    private final ClientServer client;
    private final IApplicationFactory aplicationFactory;

    public ApplicationLauncher( IApplicationFactory aplicationFactory, ClientServer client ) {
        this.aplicationFactory = aplicationFactory;
        this.client = client;
    }

    // TODO: o Server tb está criado o sample, deve estar separado
    // acredito q essa classe q deve criar
    // deve fazer client.setApplication(application);
    @Override
    public void run() {
        // Assumes that not found application
        Application application = null;
        // Inquire application name
        Message message = new Message( Protocol.MSG_NAME_INQUIRE_APPLICATION_NAME );
        Message response = client.getCommunication().inquire( message );
        String applicationName = response.getValueByName( Protocol.APPLICATION_NAME );
        // Create application from informed name
        application = aplicationFactory.createApplicationByName( applicationName );
//        // Verify appliation name and create according class
//        if (( application == null) && ( applicationName.equalsIgnoreCase( "sample" ) ))
//            application = new Sample();
        // If creates application then defines client object
        if ( application != null ) {
            
            // TODO: revisar isso, os dois tem q se referenciar?
            application.setClient( client );
            client.setApplication( application );
            // Start application
            application.run();
        }
    }
}
